package com.enjoy.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;

public class NioServerWritableHandler implements Runnable {

    private volatile boolean started;
    private Selector selector;

    public NioServerWritableHandler(int port) {
        try {
            /*创建选择器的实例*/
            selector = Selector.open();
            /*创建通道实例*/
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            /*设置通道为非阻塞模式*/
            serverSocketChannel.configureBlocking(false);
            /*绑定端口*/
            serverSocketChannel.socket().bind(new InetSocketAddress(port));
            /*注册事件*/
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

            started = true;
            System.out.println("服务器已启动,端口号:" + port);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (started) {
            try {
                /*获取当前有哪些事件,每隔一秒执行一次*/
                selector.select(1000);
                /*获取事件的集合*/
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    iterator.remove();
                    try {
                        handleInput(key);
                    } catch (IOException e) {
                        key.cancel();
                        if (key.channel() != null) {
                            key.channel().close();
                        }
                        e.printStackTrace();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /*处理事件的发生*/
    private void handleInput(SelectionKey key) throws IOException {
        System.out.println("当前的通道: " + key.interestOps());
        if (key.isValid()) {
            /*处理新接入的客户端请求*/
            if (key.isAcceptable()) {
                /*获取关心当前事件的channel*/
                ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                final SocketChannel sc = ssc.accept();
                /*设置为非阻塞*/
                sc.configureBlocking(false);
                /*注册读事件*/
                sc.register(selector, SelectionKey.OP_READ);
                System.out.println("建立连接");
            }
            /*处理对端发送的数据*/
            if (key.isReadable()) {
                SocketChannel sc = (SocketChannel) key.channel();
                final ByteBuffer buffer = ByteBuffer.allocate(1024);
                /*从通道里读数据*/
                final int readBuffer = sc.read(buffer);
                if (readBuffer > 0) {
                    /*转换为写出模式*/
                    buffer.flip();
                    byte[] bytes = new byte[buffer.remaining()];
                    /*写出数据*/
                    buffer.get(bytes);
                    String message = new String(bytes, StandardCharsets.UTF_8);
                    System.out.println("服务端接收消息:" + message);
                    doWrite(sc, message);
                } else if (readBuffer < 0) {
                    key.cancel();
                    sc.close();
                }
            }
            if (key.isWritable()) {
                SocketChannel sc = (SocketChannel) key.channel();
                ByteBuffer buffer = (ByteBuffer) key.attachment();
                if (buffer.hasRemaining()) {
                    final int count = sc.write(buffer);
                    System.out.println("write: " + count + " remain: " + buffer.remaining());
                } else {
                    /*取消对写的注册*/
                    key.interestOps(SelectionKey.OP_READ);
                }
            }
        }

    }

    private void doWrite(SocketChannel channel, String response) throws IOException {
        final byte[] bytes = response.getBytes();
        final ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
        writeBuffer.put(bytes);
        writeBuffer.flip();
        channel.register(selector, SelectionKey.OP_WRITE | SelectionKey.OP_READ, writeBuffer);
    }


}
